<!-- scr/components/Cards/EditMCard.vue -->
<template>
  <!-- 遮罩层 -->
  <div class="edit-card-overlay" @click="handleOverlayClick">
    <div class="edit-card" @click.stop>
      <!-- 顶部按钮栏 -->
      <div class="edit-card-header">
        <div class="header-left">
          <el-button 
            class="header-button delete-button" 
            @click="handleDelete" 
            type="danger" 
            text
            title="删除"
          >
            <el-icon><Delete /></el-icon>
            <span class="button-text">删除</span>
          </el-button>
        </div>
        <div class="header-right">
          <el-button 
            class="header-button close-button" 
            @click="handleClose" 
            text 
            title="关闭"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      
      <!-- 内容区域 -->
      <div class="edit-card-content">
        <!-- 标题输入框 -->
        <div class="edit-row">
          <div class="row-icon">
            <el-icon><Edit /></el-icon>
          </div>
          <el-input
            v-model="editData.title"
            type="text"
            placeholder="输入标题"
            class="title-input"
            size="large"
          />
        </div>

        <!-- 任务日期 -->
        <div class="edit-row date-row" ref="dateRowRef">
          <div class="row-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="date-content">
            <el-button 
              class="date-display" 
              @click="showDatePicker"
              text
            >
              {{ formatTaskDate() }}
            </el-button>
            <!-- DatePicker 容器 -->
            <div class="date-picker-container" v-if="showDatePickerFlag">
              <DatePicker
                :visible="showDatePickerFlag"
                :initial-date="editData.missionDate"
                @select="handleDateSelect"
                @close="hideDatePicker"
              />
            </div>
          </div>
        </div>

        <!-- 截止时间 -->
        <div class="edit-row deadline-row" ref="deadlineRowRef">
          <div class="row-icon">
            <el-icon><Flag /></el-icon>
          </div>
          <div class="deadline-section">
            <!-- 显示状态：无截止日期 -->
            <div v-if="!isEditingDeadline && !editData.deadline" class="deadline-display" @click="startEditDeadline">
              <el-button text>添加截止时间</el-button>
            </div>
            
            <!-- 显示状态：有截止日期 -->
            <div v-if="!isEditingDeadline && editData.deadline" class="deadline-display" @click="startEditDeadline">
              <el-button text>{{ formatDeadlineDate(editData.deadline) }}</el-button>
            </div>
            
            <!-- 编辑状态 -->
            <div v-if="isEditingDeadline" class="deadline-edit">
              <el-button class="deadline-date" @click="showDeadlineDatePicker" text>
                {{ formatDeadlineDate(editingDeadlineDate) }}
              </el-button>
              <el-button class="deadline-cancel-btn" @click="cancelDeadlineEdit" text>取消</el-button>
              
              <!-- 截止时间 DatePicker 容器 -->
              <div class="date-picker-container" v-if="showDeadlineDatePickerFlag">
                <DatePicker
                  :visible="showDeadlineDatePickerFlag"
                  :initial-date="editingDeadlineDate"
                  @select="handleDeadlineDateSelect"
                  @close="hideDeadlineDatePicker"
                />
              </div>
            </div>
          </div>
        </div>
        
        <!-- 备注 -->
        <div class="edit-row">
          <div class="row-icon">
            <el-icon><Document /></el-icon>
          </div>
          <el-input
            v-model="editData.remark"
            type="text"
            placeholder="添加备注"
            class="note-input"
          />
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="edit-card-footer">
        <div class="footer-left">
          <el-button 
            :type="editData.isFinished ? 'info' : 'success'" 
            @click="toggleFinishStatus"
            class="status-button"
          >
            <el-icon v-if="!editData.isFinished"><Check /></el-icon>
            <el-icon v-else><RefreshRight /></el-icon>
            {{ editData.isFinished ? '标记为未完成' : '标记为已完成' }}
          </el-button>
        </div>
        <div class="footer-right">
          <el-button class="cancel-button" @click="handleClose">
            取消
          </el-button>
          <el-button type="primary" class="save-button" @click="handleSave">
            保存
          </el-button>
        </div>
      </div>
    </div>
  </div>

  <!-- Element Plus 对话框 -->
  <el-dialog
    v-model="deleteDialogVisible"
    title="确认删除"
    width="400px"
    align-center
  >
    <span>确定要删除这个任务吗？此操作不可撤销。</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Delete,
  Close,
  Edit,
  Calendar,
  Flag,
  Document,
  Check,
  RefreshRight
} from '@element-plus/icons-vue'
import DatePicker from '@/components/Calendar/DatePicker.vue'
import type { missionCard } from '@/types/card'
import { missionCardApi } from '@/api/card'
import { useCardStore } from '@/store/card'

interface Props {
  cardData: missionCard
}

interface Emits {
  (e: 'close'): void
  (e: 'update:cardData', card: missionCard): void
  (e: 'delete', id: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const cardStore = useCardStore()

// 编辑数据
const editData = reactive<missionCard>({
  ...props.cardData
})

// DatePicker 相关状态
const showDatePickerFlag = ref(false)

// 截止时间编辑状态
const isEditingDeadline = ref(false)
const showDeadlineDatePickerFlag = ref(false)
const editingDeadlineDate = ref<Date>(new Date())

// 删除对话框状态
const deleteDialogVisible = ref(false)

// Refs for DOM elements
const dateRowRef = ref<HTMLElement | null>(null)
const deadlineRowRef = ref<HTMLElement | null>(null)

// 切换完成状态
const toggleFinishStatus = () => {
  editData.isFinished = !editData.isFinished
}

// 格式化任务日期
const formatTaskDate = () => {
  const date = editData.missionDate
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const weekDay = weekDays[date.getDay()]
  return `${month}月${day}日 周${weekDay}`
}

// 格式化截止日期
const formatDeadlineDate = (date: Date) => {
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const weekDay = weekDays[date.getDay()]
  return `${month}月${day}日 周${weekDay}`
}

// 显示日期选择器
const showDatePicker = () => {
  showDatePickerFlag.value = true
}

// 隐藏日期选择器
const hideDatePicker = () => {
  showDatePickerFlag.value = false
}

// 处理日期选择
const handleDateSelect = (date: Date) => {
  editData.missionDate = new Date(date.getTime())
  editData.date = new Date(date.getTime()) // 同时更新 date 字段
  hideDatePicker()
}

// 开始编辑截止时间
const startEditDeadline = () => {
  isEditingDeadline.value = true
  // 设置默认截止日期为任务日期的第二天，确保不早于任务日期
  const taskDate = new Date(editData.missionDate)
  const tomorrow = new Date(taskDate)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  // 如果已有截止日期且不早于任务日期，则使用已有的，否则使用默认的明天
  if (editData.deadline) {
    const deadlineDate = new Date(editData.deadline)
    deadlineDate.setHours(0, 0, 0, 0)
    taskDate.setHours(0, 0, 0, 0)
    
    if (deadlineDate >= taskDate) {
      editingDeadlineDate.value = new Date(editData.deadline)
    } else {
      editingDeadlineDate.value = tomorrow
      editData.deadline = tomorrow
    }
  } else {
    editingDeadlineDate.value = tomorrow
  }
}

// 取消截止时间编辑
const cancelDeadlineEdit = () => {
  isEditingDeadline.value = false
  // 如果当前截止日期早于任务日期，也清除它
  if (editData.deadline) {
    const deadlineDate = new Date(editData.deadline)
    deadlineDate.setHours(0, 0, 0, 0)
    const taskDate = new Date(editData.missionDate)
    taskDate.setHours(0, 0, 0, 0)
    
    if (deadlineDate < taskDate) {
      editData.deadline = undefined
    }
  }
}

// 显示截止时间DatePicker
const showDeadlineDatePicker = () => {
  showDeadlineDatePickerFlag.value = true
}

// 隐藏截止时间DatePicker
const hideDeadlineDatePicker = () => {
  showDeadlineDatePickerFlag.value = false
}

// 处理截止日期选择
const handleDeadlineDateSelect = (date: Date) => {
  // 验证截止日期不能早于任务日期
  const selectedDate = new Date(date.getTime())
  selectedDate.setHours(0, 0, 0, 0) // 只比较日期部分
  
  const taskDate = new Date(editData.missionDate)
  taskDate.setHours(0, 0, 0, 0) // 只比较日期部分
  
  if (selectedDate < taskDate) {
    ElMessage.warning('截止日期不能早于任务日期')
    // 强制设置为任务日期的后一天
    const nextDay = new Date(taskDate)
    nextDay.setDate(nextDay.getDate() + 1)
    editingDeadlineDate.value = nextDay
    editData.deadline = nextDay
  } else {
    editingDeadlineDate.value = new Date(date.getTime())
    editData.deadline = new Date(date.getTime())
  }
  
  isEditingDeadline.value = false
  showDeadlineDatePickerFlag.value = false
}

// 处理保存
const handleSave = async () => {
  try {
    // 使用 cardStore.saveMCard 来保存，这样会自动同步到任务列表
    const updatedCard = await cardStore.saveMCard({
      ...editData,
      updatedAt: new Date()
    } as missionCard)

    if (updatedCard) {
      ElMessage.success('任务更新成功')
      emit('update:cardData', updatedCard)
      emit('close')
    }
  } catch (error) {
    console.error('更新任务失败:', error)
    ElMessage.error('更新任务失败')
  }
}

// 处理删除
const handleDelete = () => {
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  emit('delete', editData.id)
  deleteDialogVisible.value = false
}

// 处理关闭
const handleClose = () => {
  emit('close')
}

// 处理遮罩层点击
const handleOverlayClick = (event: MouseEvent) => {
  // 确保点击的是遮罩层本身，而不是子元素
  if ((event.target as HTMLElement).classList.contains('edit-card-overlay')) {
    handleClose()
  }
}

// 点击外部关闭DatePicker
const handleClickOutside = (event: MouseEvent) => {
  // 关闭任务日期DatePicker
  if (showDatePickerFlag.value && dateRowRef.value && !dateRowRef.value.contains(event.target as Node)) {
    hideDatePicker()
  }
  
  // 关闭截止时间DatePicker
  if (showDeadlineDatePickerFlag.value && deadlineRowRef.value && !deadlineRowRef.value.contains(event.target as Node)) {
    hideDeadlineDatePicker()
  }
}

// 阻止背景滚动
onMounted(() => {
  document.body.style.overflow = 'hidden'
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.body.style.overflow = ''
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.edit-card-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.edit-card {
  width: 480px;
  max-height: 80vh;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部按钮栏 */
.edit-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.header-left, .header-right {
  display: flex;
  align-items: center;
}

.header-button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s ease;
  background: transparent;
}

.header-button:hover {
  transform: translateY(-1px);
}

.close-button {
  background: #f5f5f5;
  color: #666;
  font-size: 18px;
  font-weight: bold;
  padding: 6px 10px;
}

.close-button:hover {
  background: #e0e0e0;
  color: #333;
}

.delete-button {
  color: #d32f2f;
  background: rgba(211, 47, 47, 0.1);
}

.delete-button:hover {
  background: rgba(211, 47, 47, 0.2);
}

.button-icon {
  line-height: 1;
  font-size: 16px;
}

.button-text {
  font-size: 14px;
}

/* 内容区域 */
.edit-card-content {
  padding: 24px;
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.edit-row {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 0;
}

.date-row,
.deadline-row {
  position: relative;
}

.row-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  flex-shrink: 0;
  font-size: 18px;
  color: #409eff;
  background: #f0f7ff;
}

/* 输入框样式 - 移除默认的内边距 */
.title-input,
.note-input {
  flex: 1;
}

/* 深度选择器修改 Element Plus 输入框的内边距 */
.title-input :deep(.el-input__wrapper),
.note-input :deep(.el-input__wrapper) {
  padding-left: 8px;
  padding-right: 8px;
  box-shadow: 0 0 0 1px #e0e0e0 inset;
  border-radius: 6px;
}

.title-input :deep(.el-input__wrapper:hover),
.note-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.title-input :deep(.el-input__wrapper.is-focus),
.note-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.title-input :deep(.el-input__inner) {
  font-size: 16px;
  font-weight: 600;
  border: none;
  box-shadow: none;
  padding: 0;
}

.note-input :deep(.el-input__inner) {
  border: none;
  box-shadow: none;
  padding: 0;
}

/* 日期显示样式 */
.date-content {
  flex: 1;
  position: relative;
}

.date-display {
  width: 100%;
  justify-content: flex-start;
  padding: 10px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  transition: background-color 0.2s ease;
  font-size: 14px;
}

.date-display:hover {
  background: #f5f5f5;
  border-color: #409eff;
}

/* 截止时间样式 */
.deadline-section {
  flex: 1;
}

.deadline-display {
  width: 100%;
}

.deadline-display :deep(.el-button) {
  width: 100%;
  justify-content: flex-start;
  padding: 10px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  transition: background-color 0.2s ease;
  font-size: 14px;
}

.deadline-display :deep(.el-button):hover {
  background: #f5f5f5;
  border-color: #409eff;
}

.deadline-edit {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.deadline-date {
  flex: 1;
  justify-content: flex-start;
  padding: 10px 12px;
  border: 1px solid #409eff;
  border-radius: 6px;
  background: #f0f8ff;
  font-size: 14px;
}

.deadline-cancel-btn {
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background: white;
  color: #666;
  font-size: 13px;
  transition: all 0.2s ease;
}

.deadline-cancel-btn:hover {
  background: #f5f5f5;
}

/* 底部按钮 */
.edit-card-footer {
  padding: 20px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.footer-left, .footer-right {
  display: flex;
  gap: 12px;
}

.status-button {
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.save-button,
.cancel-button {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s ease;
}

.save-button:hover {
  transform: translateY(-1px);
}

.cancel-button:hover {
  background: #f5f5f5;
}

/* DatePicker 容器样式 */
.date-picker-container {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 2001;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .edit-card {
    width: 90vw;
    margin: 20px;
  }
  
  .edit-card-footer {
    flex-direction: column;
    gap: 16px;
  }
  
  .footer-left, .footer-right {
    width: 100%;
    justify-content: space-between;
  }
}
</style>